package com.sy.live.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

/**
 * 得到本机的IP地址
 * 
 * 
 */
public class GetIp
{

	private static final Logger logger = Logger.getLogger(GetIp.class);

	/**
	 * 得到本机的IP地址
	 * 
	 * @return 返回 本机的IP地址
	 */
	public static String getLocalIp()
	{
		String ipStr = "";
		Enumeration<NetworkInterface> allNetInterfaces;
		try
		{
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			while (allNetInterfaces.hasMoreElements())
			{
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements())
				{
					ip = (InetAddress) addresses.nextElement();
					if (ip != null && ip instanceof Inet4Address && !ip.toString().equals("127.0.0.1"))
					{
						ipStr = ip.getHostAddress();
						if (!ipStr.equals("127.0.0.1"))
						{
							logger.info("本机的IP = " + ip.getHostAddress());
							return ipStr;
						}
					}
				}
			}
		} catch (SocketException e)
		{
			e.printStackTrace();
		}
		return ipStr;
	}
	
	/**
	 * 获得远程IP地址
	 * @return
	 */
	public static String getRemoteIp()
	{
		String url = "http://iframe.ip138.com/ic.asp";
		
		String ip = "";
		
		HttpClient httpClient = new HttpClient();
		
		GetMethod getMethod = new GetMethod(url);
		
		try
		{
			//访问成功
			if(httpClient.executeMethod(getMethod) == HttpStatus.SC_OK)
			{
				String content = getMethod.getResponseBodyAsString();
				
				ip = content.substring(content.indexOf("[") + 1, content.indexOf("]"));
				
				logger.info("远程的IP = " + ip);
			}else
			{
				logger.info("访问" + url + "获取IP地址失败,请检查网络连接是否正常!");
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			//释放HTTP链接
			getMethod.releaseConnection();
		}
		
		return ip;
	}
	
}
